package com.globant.twittersearch;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

import com.globant.domain.SearchResponse;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class TwitterConnection {

	private final String URL_TWITTER ="https://search.twitter.com/search.json?q=";
 
	public SearchResponse obtainJson(String word) {
		HttpURLConnection urlConnection = null;
		SearchResponse timeline = null;
		try { 
			URL url = new URL(URL_TWITTER.concat(word));
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.connect();
			timeline = readStream(urlConnection.getInputStream());
		} catch (Exception e) {
			Log.e("Error", "Error in the connection with Twitter");
		} finally {
			if(urlConnection != null) {
				urlConnection.disconnect();
			}
		}
		return timeline;
	}
	

	private SearchResponse readStream(InputStream in) {

		JsonReader reader = new JsonReader(new InputStreamReader(in));
		Gson myGson = new Gson();
		return myGson.fromJson(reader, SearchResponse.class);
	} 
	
}
